package csc.daonjpa.java.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import csc.daonjpa.java.domain.Inbox;

@Service
public class InboxDAOImpl implements InboxDAO {

	@PersistenceContext
	private EntityManager entityManager;

	@Transactional
	public int numberMessageNotRead(String loginId) {
		List<Inbox> inboxs = null;
		TypedQuery<Inbox> query = entityManager.createQuery(
				"Select a from Inbox a where a.isRead = :l and a.loginIdTarget = :m", Inbox.class);
		query.setParameter("l", "New");
		query.setParameter("m", loginId);
		inboxs = query.getResultList();
		if (inboxs == null) {
			return 0;
		} else {
			return inboxs.size();
		}
	}

	@Transactional
	public List<Inbox> getInboxsSource(String loginId) {
		List<Inbox> inboxs = null;
		TypedQuery<Inbox> query = entityManager.createQuery("Select a from Inbox a Where a.customer.loginId = :m ORDER BY a.datetime DESC", Inbox.class);
		query.setParameter("m", loginId);
		inboxs = query.getResultList();
		return inboxs;
	}

	@Transactional
	public List<Inbox> getInboxs() {
		// TODO Auto-generated method stub
		return null;
	}

	@Transactional
	public boolean addInbox(Inbox inbox) {
		entityManager.persist(inbox);
		return true;
	}

	@Transactional
	public List<Inbox> getInboxsTarget(String loginId) {
		List<Inbox> inboxs = null;
		TypedQuery<Inbox> query = entityManager.createQuery("Select a from Inbox a Where a.loginIdTarget = :m ORDER BY a.datetime DESC", Inbox.class);
		query.setParameter("m", loginId);
		inboxs = query.getResultList();
		return inboxs;
	}

	@Transactional
	public Inbox getInbox(String id) {
		Query query = entityManager.createQuery("Select a from Inbox a where a.id = :i", Inbox.class);
		query.setParameter("i", id);
		Inbox inbox = (Inbox) query.getSingleResult();
		return inbox;
	}

	@Transactional
	public boolean updateInbox(Inbox inbox) {
		entityManager.merge(inbox);
		return true;
	}

}
